class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
    def to_s(self):
        # res = str(val)
        if self.next:
            self.next.to_s()
        print(self.val)

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        res, prev, tmp = l1, l1, 0
        while l1 and l2:
            tmp += l1.val + l2.val
            l1.val, tmp = tmp % 10, tmp // 10
            prev, l1, l2 = l1, l1.next, l2.next
        while l1:
            tmp += l1.val
            prev.next = ListNode(tmp % 10)
            prev, l1, tmp = prev.next, l1.next, tmp // 10
        while l2:
            tmp += l2.val
            prev.next = ListNode(tmp % 10)
            prev, l2, tmp = prev.next, l2.next, tmp // 10
        if tmp > 0:
            prev.next = ListNode(tmp)
        return res

# [9,8]
# [1]
a=ListNode(9)
a.next = ListNode(8)
# a.to_s()
b=ListNode(1)
Solution().addTwoNumbers(a,b).to_s()
